import * as React from "react";
// import { useState } from "react"
import { withRouter, Link, RouteComponentProps } from "react-router-dom";
import { observer } from 'mobx-react'
import { Modal, Button } from "antd";

import style from './style.less';
import GoodsItem from '../../components/GoodsItem';
import Order from '../../components/Order';
import img from '../../assets/imgs/car.png';
// import buy from '../../mobx/buyNum/index'
import rich from '../../mobx/richer/index'
import CountUp from "react-countup";

interface State{
//   goodsData:[];
  goodsNum:Number;
  cart: Cart[];
  show: boolean;
  showOk: boolean;
}
interface Cart {
    id: string;
    img:string;
    title: string;
    price: number;
    count:number;
    limit: number;
    weight: number;
}
@observer
export default class Home extends React.Component<RouteComponentProps>{

    countUpProps = {

        start: Number(localStorage.getItem('worth')),
        // time
        duration: 0.3,

        decimals: 0,

        useEasing: true,

        useGrouping: true,

        separator: ','
    }

    public keywords: string = '';
    public goodsIds = [];
    state:State = {
        goodsNum:0,
        cart: [],
        show: false,
        showOk: false,
    };

    //显示和关闭弹窗模块
    showModal =()=>{
        this.setState({
            show:true
        })
    }
    handleOk = () =>{
        this.setState({
            show:false,
        })
    }
    handleCancel = () =>{
        this.setState({
            show:false,
        })
    }
    handleOrderOk = () =>{
        const { history } = this.props;
        history.push('/index')
        //提交订单后清空本地订单信息。
        localStorage.setItem("orders",'');
        localStorage.setItem("money",'');
    }
    handleOrderCancel = ()=>{
        this.setState({
            showOk:false
        })
    }

    //通过判断订单实现button禁用
    getDisabled(){
        if(localStorage.getItem('money') === '' || localStorage.getItem('money') === '0'){
            return true
        }
        else{
            return false
        }
    }

    //从服务器获取商品
    async getGoods(keywords){
      let url = 'api/web/goods/search';
      let obj={};
      obj["pageIndex"]=0
      obj["pageSize"]=0
      obj["keyword"]=keywords
      let response = await fetch(url,{
          method:'POST',
          mode:'cors',
          headers:{
              'Content-Type':'application/json'
          },
          body:JSON.stringify(obj)
      })
      let res = await response.json();
      let data = [];
      if(res.stat === 'ok'){
          res.data.items.map((item) =>{
              let order = {
                  id: item.id,
                  img:item.cover,
                  title: item.title,
                  price:item.price,
                  count:0,
                  limit: parseInt(item.limit),
                  weight:parseInt(item.weight),
              }
              if(item.status != '2'){
                  data.push(order);
              }
          })
          this.setState({
              cart:data
          })
      }
      else{ 
          alert(res.msg);
      }
    }

    //向服务器提交订单数据，富豪id，goodsid[{id:"",count:},{},{}]
    async commitOrder(richId,goodsIds){
        let url='api/web/order/commit';
        let obj = {}
        obj["richId"] = richId;
        obj["goodsIds"] = JSON.parse(goodsIds);
        let response = await fetch(url,{
            method: 'POST',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json'
            },
            body:JSON.stringify(obj)
        })
        let res = await response.json();
        if( res.stat === 'ok' ){
            this.setState({
                showOk: true
            })
        }
        else{
            alert(res.msg);
        }
    }

    //得到购买的商品总数以及总金额，存储到本地
    getGoodsNum(){ 
        let total:number = 0;
        let num:number = 0;
        let data =[];
        let goodsIds =[];
        let money:number = 0;
        this.state.cart.map( (item) => {
            // console.log(item.count)
            // console.log(typeof item.count)
            let moneySingle :number= item.price * item.count;
            let obj = {
                id: item.id,
                title: item.title,
                moneySingle: moneySingle,
                count:item.count
            }
            let obj1 = {
                id: item.id,
                count:item.count
            }
            if(item.count > 0){
                data.push(obj)
                goodsIds.push(obj1)
            }
            total = total + item.count;
            money = money + moneySingle;
        } )
        // let w = parseInt(rich.worth)
        let w = parseInt(localStorage.getItem('worth'));
        rich.setnowworth(w.toString())
        let nw = w - money
        rich.setnowworth(nw.toString())
        localStorage.setItem('nowworth', nw.toString())
        // console.log(rich.nowworth)//NAN
        // console.log(rich.worth)//undefined
        localStorage.setItem('money',money.toString());
        localStorage.setItem("orders",JSON.stringify(data));
        localStorage.setItem("goodsId",JSON.stringify(goodsIds));
        return total;
    }

    //点击sell和buy时改变购物车的数字
    sell(index) {
        let copy = this.state.cart.slice();
        copy[index].count -- ;
        this.setState({
            cart: copy,
            goodsNum: this.getGoodsNum()
        })
    }
    buy(index) {
        let copy = this.state.cart.slice();
        copy[index].count ++ ;
        this.setState({
            cart: copy,
            goodsNum: this.getGoodsNum()
        })
    }
    //设置sell的禁用
    sellDisable(index){
        if(this.state.cart[index].count >0 && this.state.cart[index].count < this.state.cart[index].limit){
          return false;
        }
        else if(this.state.cart[index].count === 0){
          return true
        }
    }
    
    //设置buy的禁用
    buyDisable(index){
        if(this.state.cart[index].price > Number(localStorage.getItem('nowworth'))){
            return true;
        }
        else if(this.state.cart[index].limit === 0 ){
            return false;
        }
        else if(this.state.cart[index].count >=0 && this.state.cart[index].count < this.state.cart[index].limit){
            return false;
        }
        else{
            return true;
        }
    }

    //改变子组件中input的value，通过状态提升来实现。拷贝原接口的数据，通过事件改变value以及实现限购条件。
    getGoodsNumSingle(index,e){
        //关于状态提升
        // let str = new RegExp('[a-z]?[A-z}', 'g');
        // if(str.test(e.target.value)){
        //     alert("禁止输入字母");
        // }
        // else{
            let count = this.state.cart[index].count;
            let copy = this.state.cart.slice();
            let sum = parseInt(localStorage.getItem('nowworth')) + parseInt(localStorage.getItem('money'));
            copy[index].count = e.target.value ;
            let order = copy[index].count * copy[index].price;
            if( (parseInt(localStorage.getItem('nowworth')) + ( count * copy[index].price) - order) < 0 ){
                copy[index].count = Math.floor(parseInt(localStorage.getItem('nowworth')) / copy[index].price) + count;
            }
            else if( order > sum ){
                copy[index].count = count;
            }
            else if(this.state.cart[index].limit === 0 ){
                copy[index].count = Number(e.target.value);
            }
            else if( Number(e.target.value) > this.state.cart[index].limit ) {
                copy[index].count = this.state.cart[index].limit;
            }
            else{
                copy[index].count = Number(e.target.value);
            }
            this.setState({
                cart: copy,
                goodsNum: this.getGoodsNum()
            })
        // }
    }

    componentDidMount(){
        //刷新页面时清空购物车
        this.getGoods(this.keywords);
        localStorage.setItem("money",'');
        localStorage.setItem("orders",'');
        localStorage.setItem("nowworth", localStorage.getItem("worth"));
        localStorage.setItem("goodsId",'');
    }

    render() {
        return (
            <React.Fragment>
                <div className={style.page}>
                    {/* 购物车 */}
                    <div className={style.cart}>
                            <img 
                                src={img}
                                onClick={this.showModal}
                            />
                            <Modal 
                                title='订单详情'
                                visible = {this.state.show}
                                onCancel = { this.handleCancel }
                                centered
                                footer={[
                                    <Button type='default' onClick={this.handleCancel}>取消</Button>,
                                    <Button type='primary' disabled={this.getDisabled()} onClick={()=>{this.handleOk,this.commitOrder(localStorage.getItem('id'),localStorage.getItem('goodsId'))}}>提交</Button>
                                ]}
                            >
                                <p className={style.order_title}>Your Recipet</p>
                                {/* order组件 */}
                                {
                                    (localStorage.getItem('money') === '' || localStorage.getItem('money') === '0') ? <p className={style.order_title}>暂无订单</p> : <Order />
                                }
                                {
                                    (localStorage.getItem('money') === '' || localStorage.getItem('money') === '0') ? <span></span> :
                                    <div className={style.order}>
                                        <span>TOTAL</span>
                                        <span className={style.order_money}>${localStorage.getItem('money')}</span>
                                    </div>
                                }
                            </Modal>
                            <Modal 
                                centered
                                visible={this.state.showOk}
                                onCancel={this.handleOrderCancel}
                                closable={false}
                                footer={[
                                    <Button onClick={this.handleOrderOk}>确定</Button>
                                ]}
                            >
                                <p className={style.orderOk}>订单提交成功,{localStorage.getItem('name')}先生，您共消费{localStorage.getItem('money')}美元</p>
                            </Modal>
                        <div className={style.counter}>{this.state.goodsNum}</div>
                    </div>
                    <div className={style.container}>Neal.fun</div>
                    <div className={style.main}>
                        <div className={style.container_img}>
                            <div className={style.img}>
                                <img style={{width:'100%',height:'100%',borderRadius: '50%'}} src={`http://127.0.0.1:3000${localStorage.getItem('avatar')}`}/>
                            </div>
                            <div className={style.ttl}>Spend {localStorage.getItem('name')}' Money</div>
                        </div>
                        {/* money */}
                        <div className={style.ccontainer}>$<CountUp end={ parseInt(localStorage.getItem('nowworth')) }  {...this.countUpProps} ></CountUp></div>
                        {/* goods */}
                        <div className={style.goods}>
                        {
                            this.state.cart.sort((a,b)=>{
                                                    if(a.weight < b.weight) return -1
                                                    if(a.weight > b.weight) return 1
                                                    return 0
                                                }).map((item,index,arr) => (
                                // goodsItem作为受控子组件，通过父组件传参实现状态改变
                                <GoodsItem 
                                    item={item} 
                                    key={index} 
                                    value={this.state.cart[index].count}
                                    onChange={(e)=>this.getGoodsNumSingle(index,e)}
                                    sell={()=>this.sell(index)}
                                    buy={ ()=>this.buy(index)}
                                    buyDisable={()=>this.buyDisable(index)}
                                    sellDisable={()=>this.sellDisable(index)}
                                ></GoodsItem>)
                            )
                        } 
                        </div>
                    </div>
                    {/* 尾部 */}
                    <div className={style.footer}>
                        <div className={style.footer_header}>You may also like</div>
                        <div className={style.first_part}>
                            <a href="/deep-sea/">
                                <div className={style.a}>
                                    <div className={style.b}></div>
                                    <div className={style.first_word}>The Deep Sea</div>
                                </div>
                            </a>
                            <a href="/universe-forecast/">
                                <div className={style.a}>
                                    <div className={style.c}></div>
                                    <div className={style.first_word}>Universe Forecast</div>
                                </div>
                            </a>
                        </div>
                        <div className={style.footer_word}>"Made With"
                            <span role="img" aria-label="heart">❤️</span>
                            "by"
                            <a rel="noopener noreferrer" target="_blank" href="https://twitter.com/nealagarwal">Neal Agarwal</a>
                        </div>
                        <div className={style.footer_wo}>
                            <a href="/">Neal.fun</a>
                        </div>
                    </div>
                </div>
            </React.Fragment>
        );
    }
}
